/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.config.StatusEnum;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.Plugin;
import me.zhengjie.modules.system.domain.PluginDetail;
import me.zhengjie.modules.system.domain.vo.PluginDetailAuditVo;
import me.zhengjie.modules.system.domain.vo.PluginDetailQueryCriteria;
import me.zhengjie.modules.system.mapper.PluginDetailMapper;
import me.zhengjie.modules.system.mapper.PluginMapper;
import me.zhengjie.modules.system.service.PluginDetailService;
import me.zhengjie.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @description 服务实现
* @author lxp
* @date 2024-11-11
**/
@Service
public class PluginDetailServiceImpl extends ServiceImpl<PluginDetailMapper, PluginDetail> implements PluginDetailService {
    @Autowired
    private PluginDetailMapper pluginDetailMapper;
    @Autowired
    private PluginMapper pluginMapper;
    @Override
    public PageResult<PluginDetail> queryAll(PluginDetailQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(pluginDetailMapper.findAll(criteria, page));
    }

    @Override
    public List<PluginDetail> queryAll(PluginDetailQueryCriteria criteria){
        return pluginDetailMapper.findAll(criteria);
    }

    @Override
    public List<PluginDetail> queryByParentId(Long parentId, String status){
        LambdaQueryWrapper<PluginDetail> wrapper = new LambdaQueryWrapper();
        wrapper.eq(PluginDetail::getPluginId,parentId);
        if(StringUtils.isNotBlank(status)) {
            wrapper.eq(PluginDetail::getStatus,status);
        }
        return list(wrapper);
    }

    @Override
    public PluginDetail getPluginDetailById(Long id){
        PluginDetail pluginDetail = this.getById(id);
        if(pluginDetail == null) {
            throw new BadRequestException(" 插件版本不存在 ");
        }
        return pluginDetail;
    };

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(PluginDetail resources) {
        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PluginDetail resources) {
        PluginDetail pluginDetail = getById(resources.getId());
        pluginDetail.copy(resources);
        saveOrUpdate(pluginDetail);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean audit(PluginDetailAuditVo audit) {
        List<String> elPermissions = SecurityUtils.getCurrentUser().getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        if(!elPermissions.contains("admin") ) {
            throw new BadRequestException("只有管理员才能审批");
        }
        PluginDetail pluginDetail = this.getById(audit.getId());
        if(pluginDetail == null) {
            throw new BadRequestException(" 插件版本不存在 ");
        }
        Plugin plugin = pluginMapper.selectById(pluginDetail.getPluginId());
        if(plugin == null) {
            throw new BadRequestException(" 插件不存在 ");
        }
        if(!StatusEnum.INIT.getCode().equals(pluginDetail.getStatus())) {
            throw new BadRequestException(" 不是初始状态不能审批 ");
        }

        pluginDetail.setApproveDesc(audit.getApproveDesc());
        pluginDetail.setStatus(audit.getStatus());
        if(StatusEnum.APPROVE.getCode().equals(audit.getStatus())) {
            plugin.setStatus(StatusEnum.APPROVE.getCode());
            plugin.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
            plugin.setUpdateBy(SecurityUtils.getCurrentUserId().toString());
            plugin.setVersionLasted(pluginDetail.getVersion());
        } else if(StatusEnum.REJECT.getCode().equals(audit.getStatus())) {
            plugin.setStatus(StatusEnum.APPROVE.getCode());
        } else {
            throw new BadRequestException(" 审核状态错误 ");
        }
        this.update(pluginDetail);
        pluginMapper.updateById(plugin);
        return true;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Long> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<PluginDetail> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PluginDetail pluginDetail : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("插件ID", pluginDetail.getPluginId());
            map.put("最新版本", pluginDetail.getVersion());
            map.put("插件描述", pluginDetail.getPluginDesc());
            map.put("状态：1启用、0禁用", pluginDetail.getStatus());
            map.put("审批意见", pluginDetail.getApproveDesc());
            map.put("类型", pluginDetail.getPluginsContent());
            map.put("创建者", pluginDetail.getCreateBy());
            map.put("更新者", pluginDetail.getUpdateBy());
            map.put("创建日期", pluginDetail.getCreateTime());
            map.put("更新时间", pluginDetail.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}